package com.anolesoft.yr.mbus.cont.ctrl;

import cn.hutool.core.util.StrUtil;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.common.core.web.page.TableDataInfo;
import com.anolesoft.system.fac.entity.Employee;
import com.anolesoft.system.fac.service.IEmployeeService;
import com.anolesoft.yr.mbus.cont.entity.*;
import com.anolesoft.yr.mbus.cont.service.*;
import com.anolesoft.yr.mbus.contm.util.FileUtils;
import com.anolesoft.yr.store.stk.util.StringUtil;
import com.anolesoft.yr.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/cont")
public class ContMainController {
    private ContMainAddService contMainAddService;
    private ContMainService contMainService;
    private IEmployeeService iEmployeeService;
    private ContAppendixService contAppendixService;
    private ContMilestoneService contMilestoneService;
    private ContWordCreatService contWordCreatService;
    private ContKeyCustomerMainService contKeyCustomerMainService;
    private ContMainApproveService contMainApproveService;
    private ContVariableService contVariableService;
    @PostMapping(value = "/cont_main/add", produces = {"application/json;charset=UTF-8"})
    public AjaxResult add(@RequestBody ContMain submitData) {
        String objuid = StringUtil.generateRundom32String();
        submitData.setObjuid(objuid);
        submitData.setIsTemp(Byte.parseByte("0"));
        submitData.setContState(Byte.parseByte("0"));
        submitData.setAmountRmb(submitData.getAmount().multiply(submitData.getExchangeRate()));
        List<ContPayment> contPayments = submitData.getContPayments();
        for (int i = 0; i < contPayments.size(); i++) {
            contPayments.get(i).setContMainUid(objuid);
        }
        contMainAddService.add(submitData);
        contMilestoneService.save(
                ContMilestone.builder()
                        .contMainUid(objuid)
                        .cTime(new Date())
                        .cUserUid(SecurityUtils.getLoginUser().getEmpUid()).milestone("生成")
                        .objuid(StringUtil.generateRundom32String())
                        .build());
        return AjaxResult.success();
    }

    @PostMapping(value = "/cont_main/addAndSubmit", produces = {"application/json;charset=UTF-8"})
    public AjaxResult addAndSubmit(@RequestBody ContMain submitData) {
        String objuid = StringUtil.generateRundom32String();
        submitData.setObjuid(objuid);
        submitData.setIsTemp(Byte.parseByte("0"));
        submitData.setContState(Byte.parseByte("5"));
        submitData.setAmountRmb(submitData.getAmount().multiply(submitData.getExchangeRate()));
        List<ContPayment> contPayments = submitData.getContPayments();
        for (int i = 0; i < contPayments.size(); i++) {
            contPayments.get(i).setContMainUid(objuid);
        }
        contMainAddService.add(submitData);
        contMilestoneService.save(
                ContMilestone.builder()
                        .contMainUid(objuid)
                        .cTime(new Date())
                        .cUserUid(SecurityUtils.getLoginUser().getEmpUid()).milestone("生成并提交审批")
                        .objuid(StringUtil.generateRundom32String())
                        .build());
        return AjaxResult.success();
    }

    /**
     * 更改获取数据信息
     *
     * @param objuid
     * @return
     */
    @PostMapping(value = "/cont_main/update/get", produces = {"application/json;charset=UTF-8"})
    public ContMain get(String objuid) {
        //  ContMain contMain = contMainDao.selectByPrimaryKey(objuid);
        ContMain contMain = new ContMain();
        contMain.setDoa(BigDecimal.valueOf(1000));
        List<ContPayment> contPayments = Lists.newArrayList();
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).remark("2323232323").build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).paymentTime(new Date()).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contPayments.add(ContPayment.builder().amount(BigDecimal.valueOf(1000.00)).planAmount(BigDecimal.valueOf(2000.00)).build());
        contMain.setContPayments(contPayments);
        contMain.setBankPartyA("3232323232");
        return contMain;
    }


    /**
     * 更改获取数据信息
     *
     * @param contMain
     * @return
     */
    @PostMapping(value = "/cont_main/contUpdate", produces = {"application/json;charset=UTF-8"})
    public AjaxResult update(@RequestBody ContMain contMain) {
        contMainService.updateById(contMain);
        return AjaxResult.success();
    }


    @Transactional
    @RequestMapping(value = "/cont_main/get")
    public AjaxResult get(ContMain contMain) {
        Page<ContMain> page = new Page<>(contMain.getPage(), contMain.getRows());
        String contCode = StrUtil.nullToEmpty(contMain.getContCode());
        String customerContractCode = StrUtil.nullToEmpty(contMain.getCustomerContractCode());

        Date signDateL = contMain.getSignDateL();
        Date signDateG = contMain.getSignDateG();
        String contTypeUid = StrUtil.nullToEmpty(contMain.getContTypeUid());
        String empUid = SecurityUtils.getLoginUser().getEmpUid();
        String partAUid = StrUtil.nullToEmpty(contMain.getPartyAUid());
        String partBUid = StrUtil.nullToEmpty(contMain.getPartyBUid());
        LambdaQueryWrapper<ContMain> like = new QueryWrapper<ContMain>()
                .lambda()
                .like(ContMain::getContCode, contCode)
                .like(ContMain::getcUserUid, empUid)
                .like(ContMain::getContTypeUid, contTypeUid)
                .like(ContMain::getPartyAUid, partAUid)
                .like(ContMain::getPartyBUid, partBUid)
                .like(ContMain::getCustomerContractCode, customerContractCode)
                .orderByDesc(ContMain::getcTime);

        if (signDateL != null) {
            like.ge(ContMain::getSignDate, signDateL);
        }
        if (signDateG != null) {
            like.ge(ContMain::getSignDate, signDateG);
        }
        Page<ContMain> result = contMainService.page(page, like);
        LambdaQueryWrapper<Employee> emplike = new QueryWrapper<Employee>()
                .lambda();
        List<Employee> employees = iEmployeeService.getBaseMapper().selectList(emplike);
        Map<String, String> collect = employees.stream().collect(Collectors.toMap(Employee::getObjuid, Employee::getEmpName));
        List<ContMain> records = result.getRecords();
        log.info("查询结果:" + records);
        for (int i = 0; i < records.size(); i++) {
            if (records.get(i).getcUserUid() != null) {
                records.get(i).setcUserUid(collect.get(records.get(i).getcUserUid()));
            }
        }
        return AjaxResult.success(new TableDataInfo(result.getTotal(), records));
    }

    @Transactional
    @RequestMapping(value = "/cont_main/getComplex")
    public AjaxResult getComplex(ContMain contMain) {
        Page<ContMain> page = new Page<>(contMain.getPage(), contMain.getRows());
        String contCode = StrUtil.nullToEmpty(contMain.getContCode());
        String customerContractCode = StrUtil.nullToEmpty(contMain.getCustomerContractCode());

        Date signDateL = contMain.getSignDateL();
        Date signDateG = contMain.getSignDateG();
        String contTypeUid = StrUtil.nullToEmpty(contMain.getContTypeUid());
        String partAUid = StrUtil.nullToEmpty(contMain.getPartyAUid());
        String partBUid = StrUtil.nullToEmpty(contMain.getPartyBUid());
        LambdaQueryWrapper<ContMain> like = new QueryWrapper<ContMain>()
                .lambda()
                .like(ContMain::getContCode, contCode)
                .like(ContMain::getContTypeUid, contTypeUid)
                .like(ContMain::getPartyAUid, partAUid)
                .like(ContMain::getPartyBUid, partBUid)
                .like(ContMain::getCustomerContractCode, customerContractCode)
                .orderByDesc(ContMain::getcTime);

        if (signDateL != null) {
            like.ge(ContMain::getSignDate, signDateL);
        }
        if (signDateG != null) {
            like.ge(ContMain::getSignDate, signDateG);
        }
        Page<ContMain> result = contMainService.page(page, like);
        LambdaQueryWrapper<Employee> emplike = new QueryWrapper<Employee>()
                .lambda();
        List<Employee> employees = iEmployeeService.getBaseMapper().selectList(emplike);
        Map<String, String> collect = employees.stream().collect(Collectors.toMap(Employee::getObjuid, Employee::getEmpName));
        List<ContMain> records = result.getRecords();
        log.info("查询结果:" + records);
        for (int i = 0; i < records.size(); i++) {
            if (records.get(i).getcUserUid() != null) {
                records.get(i).setcUserUid(collect.get(records.get(i).getcUserUid()));
            }
        }
        return AjaxResult.success(new TableDataInfo(result.getTotal(), records));
    }

    @PostMapping(value = "/cont_main/upload", produces = {"application/json;charset=UTF-8"})
    public AjaxResult upload(@RequestParam("file") MultipartFile file, @RequestParam("objuid") String objuid, @RequestParam("remark") String remark) {
        String fileName = StringUtil.generateRundom32String();
        FileUtils.upload("e://temp", fileName + ".pdf", file);
        contAppendixService.save(ContAppendix.builder().address("e://temp//" + fileName + ".pdf").contMainUid(objuid).objuid(StringUtil.generateRundom32String()).uploadTime(new Date()).uploadUserUid(SecurityUtils.getLoginUser().getEmpUid()).build());
        return AjaxResult.success("上传成功");
    }

    @RequestMapping("/cont_main/fileByObj")
    @ResponseBody
    public void fileByObj(HttpServletRequest request, HttpServletResponse response) {
        String objuid = request.getParameter("objuid");
        ContAppendixExample contAppendixExample = new ContAppendixExample();
        contAppendixExample.createCriteria().andContMainUidEqualTo(objuid);
        List<ContAppendix> contAppendices = contAppendixService.selectByExample(contAppendixExample);
        String name = contAppendices.get(0).getAddress();
        String path = File.separator + name;

        File imageFile = new File(path);
        if (!imageFile.exists()) {
            return;
        }
        //下载的文件携带这个名称
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        //文件下载类型--二进制文件
        response.setContentType("application/octet-stream");
        try {
            FileInputStream fis = new FileInputStream(path);
            byte[] content = new byte[fis.available()];
            fis.read(content);
            fis.close();
            ServletOutputStream sos = response.getOutputStream();
            sos.write(content);
            sos.flush();
            sos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/cont_main/invalid")
    @ResponseBody
    public AjaxResult invalid(String objuid, String remark) {
        ContMain contMain = contMainService.getById(objuid);
        contMain.setContState(Byte.parseByte("100"));
        contMainService.updateById(contMain);
        contMilestoneService.save(
                ContMilestone.builder()
                        .contMainUid(objuid)
                        .cTime(new Date())
                        .cUserUid(SecurityUtils.getLoginUser().getEmpUid()).milestone("作废")
                        .objuid(StringUtil.generateRundom32String())
                        .remark(remark).build());
        return AjaxResult.success("作废成功");

    }
    public AjaxResult delBatch(@RequestBody List<ContVariable> contVariables){
        contVariableService.removeByIds(contVariables.stream().map(ContVariable::getObjuid).collect(Collectors.toList()));
        return AjaxResult.success("删除成功");
    }
    @Transactional
    @RequestMapping("/cont_main/approve")
    @ResponseBody
    public AjaxResult approve(@RequestBody List<ContMain> contMains) {
        contMains.forEach(a->{
            ContMain contMain = contMainService.getById(a.getObjuid());
            contMain.setContState(Byte.parseByte("10"));
            contMainService.updateById(contMain);
            contMilestoneService.save(
                    ContMilestone.builder()
                            .contMainUid(a.getObjuid())
                            .cTime(new Date())
                            .cUserUid(SecurityUtils.getLoginUser().getEmpUid()).milestone("提交审批")
                            .objuid(StringUtil.generateRundom32String())
                            .build());
        });

        return AjaxResult.success("提交审批成功！");

    }

    @RequestMapping("/cont_main/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        String objuid = request.getParameter("objuid");

        try {
            String path = contWordCreatService.executeContent(objuid);
            File imageFile = new File(path);
            if (!imageFile.exists()) {
                return;
            }
            //下载的文件携带这个名称
            response.setHeader("Content-Disposition", "attachment;filename=" + imageFile.getName());
            //文件下载类型--二进制文件
            response.setContentType("application/octet-stream");
            try {
                FileInputStream fis = new FileInputStream(path);
                byte[] content = new byte[fis.available()];
                fis.read(content);
                fis.close();
                ServletOutputStream sos = response.getOutputStream();
                sos.write(content);
                sos.flush();
                sos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Transactional
    @RequestMapping(value = "/cont_main/getByCompany", produces = {"application/json;charset=UTF-8"})
    public AjaxResult getByCompany(ContMain contMain) {
        Page<ContMain> page = new Page<>(contMain.getPage(), contMain.getRows());


        String partAUid = StrUtil.nullToEmpty(contMain.getPartyAUid());
        String partBUid = StrUtil.nullToEmpty(contMain.getPartyBUid());
        LambdaQueryWrapper<ContMain> like = new QueryWrapper<ContMain>()
                .lambda()
                .eq(ContMain::getPartyAUid, partAUid)
                .eq(ContMain::getPartyBUid, partBUid)
                .orderByDesc(ContMain::getcTime).and(Wrpper -> Wrpper.eq(ContMain::getFormalContract, "").or().isNull(ContMain::getFormalContract));
        Page<ContMain> result = contMainService.page(page, like);
        LambdaQueryWrapper<Employee> emplike = new QueryWrapper<Employee>()
                .lambda();
        List<Employee> employees = iEmployeeService.getBaseMapper().selectList(emplike);
        Map<String, String> collect = employees.stream().collect(Collectors.toMap(Employee::getObjuid, Employee::getEmpName));
        List<ContMain> records = result.getRecords();
        log.info("查询结果:" + records);
        for (int i = 0; i < records.size(); i++) {
            if (records.get(i).getcUserUid() != null) {
                records.get(i).setcUserUid(collect.get(records.get(i).getcUserUid()));
            }
        }
        return AjaxResult.success(new TableDataInfo(result.getTotal(), records));
    }

    @Transactional
    @RequestMapping(value = "/cont_main/getByFomalCodeUid", produces = {"application/json;charset=UTF-8"})
    public AjaxResult getByFomalCodeUid(ContMain contMain) {
        String formalContract = contKeyCustomerMainService.getById(contMain.getFormalContract()).getContCode();
        ContMainExample contMainExample = new ContMainExample();
        contMainExample.createCriteria().andFormalContractEqualTo(formalContract);
        List<ContMain> records = contMainService.selectByExample(contMainExample);
        LambdaQueryWrapper<Employee> emplike = new QueryWrapper<Employee>()
                .lambda();
        List<Employee> employees = iEmployeeService.getBaseMapper().selectList(emplike);
        Map<String, String> collect = employees.stream().collect(Collectors.toMap(Employee::getObjuid, Employee::getEmpName));
        for (int i = 0; i < records.size(); i++) {
            if (records.get(i).getcUserUid() != null) {
                records.get(i).setcUserUid(collect.get(records.get(i).getcUserUid()));
            }
        }
        return AjaxResult.success(new TableDataInfo(Long.parseLong("1"), records));
    }
    @RequestMapping(value = "/cont_main/approved",produces = "application/json;charset=UTF-8")
    public AjaxResult approved(String objuid) {
        ContMilestone contMilestone = ContMilestone.builder().milestone("审核完成").contMainUid(objuid).cTime(new Date()).cUserUid(SecurityUtils.getLoginUser().getEmpUid()).objuid(StringUtil.generateRundom32String()).build();
        ContMain build = ContMain.builder().contState(Byte.parseByte("15")).objuid(objuid).build();
        ContMainExample contMainExample = new ContMainExample();
        contMainExample.createCriteria().andObjuidEqualTo(objuid);
        contMainService.updateByExampleSelective(build,contMainExample);
        contMilestoneService.save(contMilestone);
        return AjaxResult.success("审批完成");
    }

    @RequestMapping(value = "/cont_main/getForApprove",produces = "application/json;charset=UTF-8")
    public AjaxResult getForApprove(String objuid){
        return contMainApproveService.getForApprove(objuid);
    }
}
